import React, { Component } from 'react'

let totalPage = 0 ,currentPage = 1

export default class Pagination extends Component {
		
	goPageClick = (page) => {
				if( page === 'next'){
					if ( totalPage === this.props.current){
							page = totalPage
							return
					}else{
						page = this.props.current + 1
					}
				} else if (page === 'prev'){
					if (totalPage === this.props.current) {
						page = totalPage
						return
					} else {
						page = this.props.current - 1
					}
				}

				
		this.props.onChange && this.props.onChange(page, this.props.pageSize)
	}
	
  render() {

		let totalPage = 0 , pageArr = [], start ,end
			
		const { current =1, pageSize =10, total=0} = this.props
		totalPage = Math.ceil(total / pageSize)
				// console.log(totalPage)

		start = current - 2
		end = current + 2

		if (start < 2)
		 start = 2

		if (end < 5)
		 end = 5

		if(( start+4 )> totalPage) {
				start = totalPage - 4
		}

		if (end >= totalPage) {
			end = totalPage-1
		}

		
		for(let i = start; i<= end; i++){

			pageArr.push(<li
				 className={ current == i ? 'active' :''}
				 key={"lis"+ i}
				 onClick={this.goPageClick.bind(null,i)}
				 ><a href="#">{i}</a></li>)
		}

    return (
        <nav>
				    <ul className="pagination pagination-sm no-margin pull-right">
				     	<li className={ currentPage === current ? 'disabled' : ''} 
								onClick={this.goPageClick.bind(null,'prev')}>
                    <a href="#">
                        <span>&laquo;</span>
                    </a>
                        </li>

					         <li className={current === 1 ? 'active' : ''} onClick={this.goPageClick.bind(null, 1)}> 
									 <a href="javascript:;">1</a></li>

								{
					      	 (current > 4) && <li><a href="javascript:;">...</a></li>
								}
					    
								{ pageArr }

								{
					        (end < totalPage-1 )&&<li><a href="javascript:;">...</a></li>
								}
					     
					      <li className={current === totalPage ? 'active' : ''} onClick={this.goPageClick.bind(null, totalPage)}><a href="javascript:;">{totalPage}</a></li>

								<li className={totalPage === current ? 'disabled' : '' } 
								onClick={this.goPageClick.bind(null,'next')}>
                    <a href="javascript:;">
                        <span>&raquo;</span>
                    </a>
                </li>
            </ul>
        </nav>
    )
  }
}


